#!/usr/bin/python3

"""
MIT License

Copyright (c) 2025 milkpotatoes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

"""Build and run tests."""

from pathlib import Path
import argparse
import sys
import subprocess

PROJECT_ROOT = Path(__file__).parent.parent
ARG_PARSER = argparse.ArgumentParser(description="Build and run tests.")
ARG_PARSER.add_argument(
    "--build-dir",
    "-b",
    type=str,
    help="Directory of napi_runner build directory.",
    required=True,
)
ARG_PARSER.add_argument(
    "--es2abc-path",
    "-e",
    type=str,
    help="Path to es2abc.",
    required=True,
)
ARG_PARSER.add_argument(
    "--level",
    "-l",
    choices=[f"L{i}" for i in range(5)] + [f"@L{i}" for i in range(5)]+ [f"!L{i}" for i in range(5)],
    metavar="LEVEL",
    help="Test level: Lx, @Lx, or !Lx (x=0-4). Lx=up to x, @Lx=only x, !Lx=exclude x. Default: L4.",
    default="L4",
    required=False,
)

ARG_PARSER.add_argument(
    "--ark-options",
    type=str,
    help="Arguments for js_vm (without perfix '--'). Example: --ark-options compiler-enable-jit=true.",
    nargs="+",
)
ARG_PARSER.add_argument(
    "--filter", "-f", type=str, help="Filter of testsuit.", default="*"
)


def build(es2abc_path: Path, file: Path, base_dir: Path, out_dir: Path) -> Path | None:
    abc = out_dir / file.relative_to(base_dir).with_suffix(".abc")
    out_dir.mkdir(parents=True, exist_ok=True)
    abc.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run([es2abc_path, "--module", file, "--output", abc], check=True)
    return abc


def run(napi_runner: Path, abc: Path, cwd: Path, arkOptions: list, args: list) -> None:
    cmds = [napi_runner]
    for option in arkOptions:
        cmds += ("-k", "--" + option)
    cmds.append(abc)
    cmds += args
    subprocess.run(cmds, cwd=cwd, check=True)


def main():
    args = ARG_PARSER.parse_args(sys.argv[1:])
    BUILD_DIR = Path(args.build_dir)
    ES2ABC_PATH = Path(args.es2abc_path).resolve()
    FILTER = args.filter
    TEST_DIR = PROJECT_ROOT / "tests"
    ARK_OPTIONS = [] if args.ark_options is None else args.ark_options
    NAPI_RUNNER = BUILD_DIR / "napi_runner"
    TEST_LEVEL = args.level
    if not NAPI_RUNNER.exists():
        print(f"napi_runner not found in {NAPI_RUNNER}")
        return
    for file in TEST_DIR.glob("utils/*.ts"):
        build(ES2ABC_PATH, file, TEST_DIR, BUILD_DIR / "tests")
    ran = 0
    for file in TEST_DIR.glob("**/*.test.ts"):
        if not file.match(FILTER):
            continue
        print(f"Building {file}...")
        abc = build(ES2ABC_PATH, file, TEST_DIR, BUILD_DIR / "tests")
        if abc is None:
            continue
        print(f"Running {abc}...")
        run(
            NAPI_RUNNER.resolve(),
            abc.resolve(),
            BUILD_DIR / "tests",
            ARK_OPTIONS,
            [TEST_LEVEL],
        )
        print()
        ran += 1
    print(f"No error after {ran} testsuits ran.")


if __name__ == "__main__":
    main()
